<?php
namespace lib;
class Http {
	private $client = null;
	private $gatewayConfig = null;
	private $header = ['Content-Type' => 'application/json'];
	private $setOption = ['timeout' => 50];
	
	public function __construct($gateway = 1) {
	    $this->gatewayConfig = Config::$gateway;
	    $this->client = new \Swoole\Coroutine\Http\Client($this->gatewayConfig['host'][$gateway - 1], $this->gatewayConfig['port']);
	}
	
	
	public function close() {
		$this->client->close();
	}
	
	public function body() {
		return $this->client->body;
	}
	
	public function post($url, $data) {
		if(is_array($data)) {
			$data = json_encode($data);
		}
		
		$this->client->setHeaders($this->header);
		$this->client->set($this->setOption);
		
		$this->client->post('/' . $this->gatewayConfig['prefix'] . '/' .  $url, $data);
		
		$body = $this->client->body;
		if(strtolower($body) === 'error'){
		    return $body;
		}elseif($body === ''){
		    return null;
		}
		
		return $body;
	}
}